package tgc.edu.yzy.controller;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.forte.qqrobot.beans.messages.types.GroupAddRequestType;

import tgc.edu.yzy.CqrobotIndependentApplication;
import tgc.edu.yzy.Impl.GroupListImpl;
import tgc.edu.yzy.Impl.GroupRequestImpl;
import tgc.edu.yzy.Impl.LexiconImpl;
import tgc.edu.yzy.Impl.OpenLayoutImpl;
import tgc.edu.yzy.Impl.QqRobotSetImpl;
import tgc.edu.yzy.bean.GroupList;
import tgc.edu.yzy.bean.GroupRequest;
import tgc.edu.yzy.bean.Lexicon;
import tgc.edu.yzy.bean.OpenLayout;
import tgc.edu.yzy.bean.QqRobotSet;
import tgc.edu.yzy.custom.AjaxResult;
import tgc.edu.yzy.custom.BackEndHttpRequest;
import tgc.edu.yzy.custom.HtmlAndQq;
import tgc.edu.yzy.custom.QqCqcustom;
import tgc.edu.yzy.custom.TimeUtils;
import tgc.edu.yzy.custom.UpdateGroupList;

@Controller
public class HomeController {
	 @Autowired
    public GroupListImpl groupImpl;
    @Autowired
    public QqRobotSetImpl robotset;
    @Autowired
    public LexiconImpl lexicon;
    @Autowired
    public OpenLayoutImpl openimpl;
    @Autowired
    public GroupRequestImpl requestimpl;
	
	@RequestMapping({ "/coc" })
    @CrossOrigin(allowedHeaders = { "*" }, allowCredentials = "true")
    @ResponseBody
    public String coc(final String url) {
        return BackEndHttpRequest.sendGetCoc(url);
    }
	@RequestMapping({ "/grouprequest" })
    @CrossOrigin(allowedHeaders = { "*" }, allowCredentials = "true")
    @ResponseBody
    public Object grouprequest() {
        final List<GroupRequest> list =this.requestimpl.query().eq("type", "1").orderByDesc("id").list();
        final HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("code", 0);
        result.put("number", list.size());
        result.put("count", list.size());
        result.put("data", list);
        return result;
    }
	
	@RequestMapping({ "/grouprequestYes" })
    @CrossOrigin(allowedHeaders = { "*" }, allowCredentials = "true")
    @ResponseBody
    public Object grouprequestYes(final Integer id, final String type, final String name) {
        final GroupRequest one = this.requestimpl.query().eq("id", id).eq("type", "1").one();
        if (one == null) {
            return null;
        }
        one.setCreateName(name);
        one.setCreateDate(TimeUtils.getStringDate());
        if (type == null) {
        	MyqqRobot.groupList.add(one.getGroupcode());
            final GroupAddRequestType requestType = GroupAddRequestType.INVITE;
            final String flag = one.getFlag();
            CqrobotIndependentApplication.msgSender.SETTER.setGroupAddRequest(flag, requestType, true, flag);
            one.setType("已同意");
            this.requestimpl.updateById(one);
            
            //保存经过人工审核的状态
            UpdateGroupList.uodate(CqrobotIndependentApplication.msgSender, MyqqRobot.cqCodeUtil);
        }
        else {
            one.setType("忽略");
            this.requestimpl.updateById(one);
        }
        return null;
    }
	
	/***
	 * 获取群列表
	 * @return
	 */
	@RequestMapping(value="/grouplist")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object groupList() {
		List<GroupList> list = groupImpl.list();
		HashMap<String, Object> result=new HashMap<>();
		result.put("code", 0);
		result.put("number",list.size());
		result.put("count",list.size());
		result.put("data",list);
		return result;
	}
	/***
	 * 获取
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping(value="/broadcast")
	@ResponseBody
	public Object broadcast() throws InterruptedException {
		List<GroupList> list = groupImpl.query().eq("isfalsetrue", "在群").list();
		for (GroupList groupList : list) {
			int max=6000,min=0;
			int r = (int) (Math.random()*(max-min)+min); 
			Thread.sleep(r);
			System.out.println(groupList.getGroupcode());
		}
		return list;
	}
	/****
	 * 删除群
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/delete")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object delete(Integer id) {
		try {
			GroupList group = new GroupList();
			group.setId(id);
			groupImpl.removeById(group);
			return new AjaxResult("数据删除成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据删除失败");
		}
	}
	/****
	 *  群广播专用
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/tobroadcast")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object tobroadcast(String group,String msg) {
		try {
			msg = HtmlAndQq.broadcastGroup(msg, group, CqrobotIndependentApplication.msgSender);
			boolean sendGroupMsg = CqrobotIndependentApplication.msgSender.SENDER.sendGroupMsg(group, msg);
			return new AjaxResult(sendGroupMsg, "消息发送成功");
		} catch (Exception e) {
			return new AjaxResult(false, "消息发送失败");
		}
	}
	/****
	 * 更新机器人加入的群
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/updaterobotgroup")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object updaterobotgroup() {
		try {
			groupImpl.updateAll();
			UpdateGroupList.uodate(CqrobotIndependentApplication.msgSender, MyqqRobot.cqCodeUtil);
			return new AjaxResult(false, "数据更新成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据更新失败");
		}
	}
	/***
	 * 退出群聊
	 * @param group
	 * @return
	 */
	@RequestMapping(value="/groupLeave")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Boolean groupLeave(String group,String value) {
		try {
			CqrobotIndependentApplication.msgSender.SENDER.sendGroupMsg(group, value);
			CqrobotIndependentApplication.msgSender.SETTER.setGroupLeave(group);
			UpdateGroupList.uodate(CqrobotIndependentApplication.msgSender, MyqqRobot.cqCodeUtil);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/***
	 * 退出群聊
	 * @param group
	 * @return
	 */
	@RequestMapping(value="/updategroup")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Boolean updategroup(String group) {
		try {
			boolean updateGroupList = QqCqcustom.updateGroupList(CqrobotIndependentApplication.msgSender,group);
			return updateGroupList;
		} catch (Exception e) {
			return false;
		}
	}
	/****
	 * 机器人配置
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/qqrobotset")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public QqRobotSet qqrobotset() {
		QqRobotSet se = new QqRobotSet();
		se.setId(1);
		return robotset.getById(se);
	}
	/****
	 * 机器人配置修改
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/robotsave")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	private Boolean robotsave(QqRobotSet form, Integer id) {
		if (form.getId() == 1) {
			QqRobotSet qq = robotset.getById(form);
			BeanUtils.copyProperties(form, qq);
			robotset.updateById(qq);
			return true;
		}
		return false;
	}
	@RequestMapping(value = {"/login", "/"}, method = RequestMethod.GET)
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public String login() {
		return "ok";
	}
	/****
	 * 	词库列表
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/lexiconlist")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object lexiconlist() {
		List<Lexicon> list = lexicon.list();
		HashMap<String, Object> result=new HashMap<>();
		result.put("code", 0);
		result.put("number",list.size());
		result.put("count",list.size());
		result.put("data",list);
		return result;
	}
	/****
	 * 删除所有词库
	 * @return
	 */
	@RequestMapping(value="/deleteAll")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object deleteAll(Integer id) {
		if(id!=null) {
			Lexicon le = new Lexicon();
			le.setId(id);
			lexicon.removeById(le);
		}else {
			lexicon.deleteAll();
		}
		return true;
	}
	
	
	
	/****
	 * 同步所有词库
	 * @return
	 */
	@RequestMapping(value="/updateLexicon")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object updateLexicon(Integer id) {
		try {
			MyqqRobot.list = lexicon.query().eq("type", "模糊").eq("isuser", "1").ne("number", "随机").list();
			CqrobotIndependentApplication.msgSender.SENDER.sendPrivateMsg(MyqqRobot.administratorQQ, "词库已加载完毕！\n"
					+ "全发："+MyqqRobot.list.size()+"条数据");
			return true;
		} catch (Exception e) {	
			CqrobotIndependentApplication.msgSender.SENDER.sendPrivateMsg(MyqqRobot.administratorQQ, "词库加载失败");
			return false;
		}
	}
	@RequestMapping(value="/toisusersave")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public Object toisusersave(Integer formids,Boolean isgoto) {
		try {
			if(formids==null||isgoto==null) {
				return false;
			}else {
				lexicon.update().eq("id", formids).set("isuser", isgoto).update();
				return true;
			}
		} catch (Exception e) {	
			e.printStackTrace();
			return false;
		}
	}
	/***
	 * 导入第二个用户的词库
	 * @param data
	 * @param user
	 * @param request
	 * @return
	 */
	//private ObjectMapper mapper = new ObjectMapper();
	@RequestMapping(value="/batchProcessing")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	private Object batchProcessing(String data,String user,HttpServletRequest request) {
		try {
			//List<Lexicon> list = mapper.readValue(data,new TypeReference<List<Lexicon>>() { });
			JSONArray parseArray = JSON.parseArray(data); 
			
			int sum = 0;
			for (int i = 0; i < parseArray.size(); i++) {  
				JSONObject jo = parseArray.getJSONObject(i); 
				Lexicon l =  new Lexicon();
				l.setId(null);
				l.setCreateDate(TimeUtils.getStringDate()+"");
				l.setCreateName("批量导入1");
				l.setAntistop(jo.getString("antistop"));
				l.setResponse(jo.getString("response"));
				l.setType(jo.getString("type"));
				l.setNumber(jo.getString("number"));
				l.setIsuser(true);
				l.setSum(0);
				lexicon.save(l);
				sum ++;
			}
			String msg = "成功导入 "+sum+" 条数据！";
			if(sum!=parseArray.size()) {
				msg +="失败 "+(parseArray.size() - sum)+" 条数据！";
			}
			return new AjaxResult(msg);
		} catch (Exception e) {
			return new AjaxResult(false,"导入失败！非法操作，错误203；");
		}
	}
	
	/** 有关阵型的 **/
	/*@RequestMapping(value="/deleteAllOP")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	private String deleteopAll() {
		openimpl.delete();
		return openimpl.updateQt();
	}*/
	
	//新增阵型
	/*@RequestMapping(value="/setzx")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public String setzx(OpenLayout openlayou) {
		openimpl.save(openlayou);
		return "ok";
	}
	
	*//***
	 * 删除阵型
	 * @param id
	 * @return
	 *//*
	@RequestMapping(value="/openremove")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public String openremove(Integer id) {
		openimpl.removeById(id);
		return "ok";
	}
	*//***
	 * 删除阵型
	 * @param id
	 * @return
	 *//*
	@RequestMapping(value="/openremovelist")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public List<OpenLayout> openremovelist(Integer id) {
		List<OpenLayout> list = openimpl.list();
		return list;
	}
	*//***
	 * 删除阵型
	 * @param id
	 * @return
	 *//*
	@RequestMapping(value="/findByNumber")
	@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
	@ResponseBody
	public List<OpenLayout> findByNumber(String number) {
		List<OpenLayout> list = openimpl.query().eq("number", number).list();
		return list;
	}*/
}
